package com.android.cattlefarm;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.cattlefarm.db.AddDB;
import com.android.cattlefarm.db.ImportDB;
import com.android.cattlefarm.util.Constants;
import com.android.cattlefarm.util.ExportEntity;
import com.android.cattlefarm.util.ImportEntity;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


/**
 * Created by Huang on 2015/7/6.
 */
public class AddActivity extends Activity {
    static int cows[][] = {
            {57, 64, 70, 75, 85, 90, 95, 100, 95},//体高
            {55, 60, 65, 70, 75, 80, 85, 90, 95},//胸宽
            {56, 64, 68, 75, 80, 90, 95, 90, 85},//体深
            {55, 60, 65, 70, 75, 80, 85, 90, 95},//腰强度
            {55, 62, 70, 80, 90, 80, 75, 70, 65},//尻角度
            {55, 60, 65, 70, 75, 79, 82, 90, 95},//尻宽
            {56, 64, 70, 76, 81, 90, 100, 95, 85},//蹄角度
            {57, 64, 69, 75, 80, 85, 90, 95, 100},//蹄踵深度
            {57, 64, 69, 75, 80, 85, 90, 95, 100},//骨质地
            {55, 64, 75, 80, 95, 80, 75, 65, 55},//后肢侧视
            {57, 64, 69, 74, 78, 81, 85, 90, 100},//后肢后视
            {55, 65, 75, 85, 95, 85, 75, 65, 55},//乳房深度
            {55, 60, 65, 70, 75, 80, 85, 90, 95},//中央悬韧带
            {55, 60, 65, 70, 75, 80, 85, 90, 95},//前乳房附着
            {57, 65, 75, 80, 85, 90, 85, 80, 75},//前乳头位置
            {50, 60, 70, 80, 90, 80, 70, 60, 50},//前乳头长度
            {58, 65, 68, 70, 75, 80, 85, 90, 95},//后乳房附着高度
            {58, 65, 68, 70, 75, 80, 85, 90, 95},//后乳房附着宽度
            {57, 65, 75, 80, 85, 90, 85, 80, 75},//后乳头位置
            {57, 64, 69, 74, 78, 81, 85, 90, 95} //棱角性
    };

    static String[] names = {
            "体高",
            "胸宽",
            "体深",
            "腰强度",
            "尻角度",
            "尻宽",
            "蹄角度",
            "蹄踵深度",
            "骨质地",
            "后肢侧视",
            "后肢后视",
            "乳房深度",
            "中央悬韧带",
            "前乳房附着",
            "前乳头位置",
            "前乳头长度",
            "后乳房附着高度",
            "后乳房附着宽度",
            "后乳头位置",
            "棱角性"

    };

    private RadioGroup radioGroup1,
            radioGroup2,
            radioGroup3,
            radioGroup4,
            radioGroup5,
            radioGroup6,
            radioGroup7,
            radioGroup8,
            radioGroup9,
            radioGroup10,
            radioGroup11,
            radioGroup12,
            radioGroup13,
            radioGroup14,
            radioGroup15,
            radioGroup16,
            radioGroup17,
            radioGroup18,
            radioGroup19,
            radioGroup20;
    private AutoCompleteTextView cowNum;
    private TextView cowFarmNum, birthday, tyre, productionTime;
    private View groupView;

    private int current[] = new int[20];

    private List<ExportEntity> dataList;
    private List<String> keys;
    private HashMap<String, ExportEntity> maps = new HashMap<>();
    private ExportEntity currentEntity;

    InputMethodManager imm ;
    private ArrayAdapter<String> av;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        current = new int[20];
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);


        initViews();
        keys = new ArrayList<>();

        initListener();
        initData();
        init();
    }

    private void initData(){
        AddDB importDB = new AddDB(this);

        dataList = importDB.queryExportList();
        importDB.closeDataBase();
        if (dataList != null && dataList.size() > 0) {
            keys.clear();
            maps.clear();
            for (ExportEntity importEntity : dataList) {
                if(importEntity.getAverage() <= 0.0f) {
                    keys.add(importEntity.getCowNum());
                    maps.put(importEntity.getCowNum(), importEntity);
                }
            }
            cowNum.setAdapter(new ArrayAdapter<>(this,
                    android.R.layout.simple_dropdown_item_1line, keys));
        }
    }
    private void initViews() {
        radioGroup1 = (RadioGroup) findViewById(R.id.checkbox_0);
        radioGroup2 = (RadioGroup) findViewById(R.id.checkbox_1);
        radioGroup3 = (RadioGroup) findViewById(R.id.checkbox_2);
        radioGroup4 = (RadioGroup) findViewById(R.id.checkbox_3);
        radioGroup5 = (RadioGroup) findViewById(R.id.checkbox_4);
        radioGroup6 = (RadioGroup) findViewById(R.id.checkbox_5);
        radioGroup7 = (RadioGroup) findViewById(R.id.checkbox_6);
        radioGroup8 = (RadioGroup) findViewById(R.id.checkbox_7);
        radioGroup9 = (RadioGroup) findViewById(R.id.checkbox_8);
        radioGroup10 = (RadioGroup) findViewById(R.id.checkbox_9);
        radioGroup11 = (RadioGroup) findViewById(R.id.checkbox_10);
        radioGroup12 = (RadioGroup) findViewById(R.id.checkbox_11);
        radioGroup13 = (RadioGroup) findViewById(R.id.checkbox_12);
        radioGroup14 = (RadioGroup) findViewById(R.id.checkbox_13);
        radioGroup15 = (RadioGroup) findViewById(R.id.checkbox_14);
        radioGroup16 = (RadioGroup) findViewById(R.id.checkbox_15);
        radioGroup17 = (RadioGroup) findViewById(R.id.checkbox_16);
        radioGroup18 = (RadioGroup) findViewById(R.id.checkbox_17);
        radioGroup19 = (RadioGroup) findViewById(R.id.checkbox_18);
        radioGroup20 = (RadioGroup) findViewById(R.id.checkbox_19);

        cowNum = (AutoCompleteTextView) findViewById(R.id.add_cow_num);
        cowFarmNum = (TextView) findViewById(R.id.cow_forum_num);
        birthday = (TextView) findViewById(R.id.cow_birthday);
        tyre = (TextView) findViewById(R.id.cow_tyre);
        productionTime = (TextView) findViewById(R.id.cow_producetime);
        groupView = findViewById(R.id.cow_left_ll);
    }

    private void initListener() {

        radioGroup1.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup2.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup3.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup4.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup5.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup6.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup7.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup8.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup9.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup10.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup11.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup12.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup13.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup14.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup15.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup16.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup16.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup17.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup18.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup19.setOnCheckedChangeListener(checkedChangeListener);
        radioGroup20.setOnCheckedChangeListener(checkedChangeListener);
        cowNum.setOnItemClickListener(itemClickListener);
        groupView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                return false;
            }
        });
    }

    private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            currentEntity = maps.get(cowNum.getAdapter().getItem(position).toString());
            hideKeyboard();
            currentInfo();
        }
    };


    private void currentInfo() {
        if (currentEntity != null) {
            cowFarmNum.setText(currentEntity.getCowfarmNum());
            birthday.setText(currentEntity.getBirthday());
            tyre.setText(currentEntity.getTyre());
            productionTime.setText(currentEntity.getProductionTime());
        }
    }

    public void saveClick(View v) {
        boolean saveT = true;
        for (int i = 0; i < current.length; i++) {
            if (current[i] == 0) {
                showMessage(names[i] + "  还未选择");
                saveT = false;
                break;
            }
        }
        if (saveT)
            save();
    }

    private void save() {
        if (currentEntity == null) {
            showMessage("请先输入牛号");
            return;
        }
        try {
            ExportEntity entity = currentEntity;
            ExportEntity exportEntity = new ExportEntity();
            exportEntity.setTyre(entity.getTyre());
            exportEntity.setProductionTime(entity.getProductionTime());
            exportEntity.setMother(entity.getMother());
            exportEntity.setBirthday(entity.getBirthday());
            exportEntity.setCowfarmName(entity.getCowfarmName());
            exportEntity.setCowfarmNum(entity.getCowfarmNum());
            exportEntity.setCowNum(entity.getCowNum());
            exportEntity.setFather(entity.getFather());
            exportEntity.setGrandfather(entity.getGrandfather());
            exportEntity.setColumnValue(current);
            exportEntity.setTiqurongliang(getTiqurongliang());
            exportEntity.setKaobu(getKaobu());
            exportEntity.setZhiti(getZhiti());
            exportEntity.setQianrufang(getQianrufang());
            exportEntity.setHourufang(getHourufang());
            exportEntity.setXitong(getXitong(exportEntity));
            exportEntity.setRuyongtezheng(cows[19][current[19] - 1]);
            exportEntity.setAverage(getAverage(exportEntity));
            AddDB addDB = new AddDB(this);
            long l = addDB.insertExport(exportEntity);
            if (l > 0) {
                showMessage("保存成功");
                try {
                    if(entity.getCowNum() != null)
                    keys.remove(entity.getCowNum());
                    cowNum.setAdapter(new ArrayAdapter<>(this,
                            android.R.layout.simple_dropdown_item_1line, keys));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                clear();
            } else {
                showMessage("保存失败,请重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            showMessage("保存失败,请重试");
        }

    }

    private float getTiqurongliang() {
        float x = 0f;
        x = 0.25f * cows[0][current[0] - 1] + 0.35f * cows[1][current[1] - 1]
                + 0.25f * cows[2][current[2] - 1]
                + 0.15f * cows[3][current[3] - 1];
        return getDouFloat(x);
    }

    private float getKaobu() {
        float x = 0f;
        x = 0.4f * cows[4][current[4] - 1] + 0.45f * cows[5][current[5] - 1]
                + 0.15f * cows[3][current[3] - 1];
        return getDouFloat(x);
    }

    private float getZhiti() {
        float x = 0f;
        x = 0.25f * cows[6][current[6] - 1]
                + 0.1f * cows[7][current[7] - 1]
                + 0.2f * cows[8][current[8] - 1]
                + 0.25f * cows[9][current[9] - 1]
                + 0.2f * cows[10][current[10] - 1];
        return getDouFloat(x);
    }

    private float getQianrufang() {
        float x = 0f;
        x = 0.45f * cows[13][current[13] - 1]
                + 0.25f * cows[14][current[14] - 1]
                + 0.18f * cows[15][current[15] - 1]
                + 0.12f * cows[11][current[11] - 1];
        return getDouFloat(x);
    }

    private float getHourufang() {
        float x = 0f;
        x = 0.3f * cows[16][current[16] - 1]
                + 0.3f * cows[17][current[17] - 1]
                + 0.14f * cows[18][current[18] - 1]
                + 0.12f * cows[11][current[11] - 1]
                + 0.14f * cows[12][current[12] - 1];
        BigDecimal b = new BigDecimal(x);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return getDouFloat(x);
    }

    private float getXitong(ExportEntity exportEntity) {
        float x = 0f;
        float y = 0.55f * cows[11][current[11] - 1] + 0.45f * cows[12][current[12] - 1];
        x = y * 0.20f + exportEntity.getQianrufang() * 0.35f + exportEntity.getHourufang() * 0.45f;
        return getDouFloat(x);
    }

    private float getAverage(ExportEntity exportEntity) {
        float x = 0f;
        x = 0.18f * exportEntity.getTiqurongliang()
                + 0.1f * exportEntity.getKaobu()
                + 0.20f * exportEntity.getZhiti()
                + 0.4f * exportEntity.getXitong()
                + 0.12f * exportEntity.getRuyongtezheng();
        return getDouFloat(x);
    }

    private float getDouFloat(float f) {
        BigDecimal b = new BigDecimal(f);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return f1;
    }

    private RadioGroup.OnCheckedChangeListener checkedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            hideKeyboard();
            int gg = 0;
            switch (group.getId()) {
                case R.id.checkbox_0:
                    gg = 0;
                    break;
                case R.id.checkbox_1:
                    gg = 1;
                    break;
                case R.id.checkbox_2:
                    gg = 2;
                    break;
                case R.id.checkbox_3:
                    gg = 3;
                    break;
                case R.id.checkbox_4:
                    gg = 4;
                    break;
                case R.id.checkbox_5:
                    gg = 5;
                    break;
                case R.id.checkbox_6:
                    gg = 6;
                    break;
                case R.id.checkbox_7:
                    gg = 7;
                    break;
                case R.id.checkbox_8:
                    gg = 8;
                    break;
                case R.id.checkbox_9:
                    gg = 9;
                    break;
                case R.id.checkbox_10:
                    gg = 10;
                    break;
                case R.id.checkbox_11:
                    gg = 11;
                    break;
                case R.id.checkbox_12:
                    gg = 12;
                    break;
                case R.id.checkbox_13:
                    gg = 13;
                    break;
                case R.id.checkbox_14:
                    gg = 14;
                    break;
                case R.id.checkbox_15:
                    gg = 15;
                    break;
                case R.id.checkbox_16:
                    gg = 16;
                    break;
                case R.id.checkbox_17:
                    gg = 17;
                    break;
                case R.id.checkbox_18:
                    gg = 18;
                    break;
                case R.id.checkbox_19:
                    gg = 19;
                    break;
            }
            View radioButton = group.findViewById(group.getCheckedRadioButtonId());
            if (radioButton != null) {
                try {
                    int child = Integer.parseInt(radioButton.getTag().toString());
                    if (child > 0) {
                        current[gg] = child;
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    private void clear() {
        radioGroup1.clearCheck();
        radioGroup2.clearCheck();
        radioGroup3.clearCheck();
        radioGroup4.clearCheck();
        radioGroup5.clearCheck();
        radioGroup6.clearCheck();
        radioGroup7.clearCheck();
        radioGroup8.clearCheck();
        radioGroup9.clearCheck();
        radioGroup10.clearCheck();
        radioGroup11.clearCheck();
        radioGroup12.clearCheck();
        radioGroup13.clearCheck();
        radioGroup14.clearCheck();
        radioGroup15.clearCheck();
        radioGroup16.clearCheck();
        radioGroup17.clearCheck();
        radioGroup18.clearCheck();
        radioGroup19.clearCheck();
        radioGroup20.clearCheck();
        current = new int[20];
        init();
    }

    private void init() {
        for (int i = 0; i < 20; i++) {
            current[i] = 0;
        }
        currentEntity = null;
        cowNum.setText("");
        cowFarmNum.setText("");
        birthday.setText("");
        tyre.setText("");
        productionTime.setText("");
        showKeyboard();

    }

    private void showMessage(String str) {
        Toast toast = new Toast(this);
        View toastView = LayoutInflater.from(this).inflate(R.layout.toast_text,null);
        TextView textView = (TextView) toastView.findViewById(R.id.toast_text);
        textView.setText(str);
        toast.setView(toastView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 10);
        toast.show();
    }

    private void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    private void showKeyboard(){
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) {
            if (getCurrentFocus() != null)
                imm.showSoftInput(cowNum, InputMethodManager.SHOW_IMPLICIT);
        }
    }
}
